package com.cdream.basic.java8.io;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author cdream
 * @date 2022/8/15
 */
@Slf4j
public class SocketServer {
    private static final Integer PORT = 18080;
    private static final String HOST = "localhost";
    private static final String QUIT = "QUIT";

    public static void main(String[] args) {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(PORT);
            log.info("服务端启动，监听端口号：{}", PORT);

            while (true) {
                Socket accept = ss.accept();
                log.info("客户端已连接，ip：{}，port: {}", accept.getInetAddress().getHostName(), accept.getPort());
                BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream()));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    log.info("从客户端读取到数据:{}", line);
                    bw.write("客户端收到：" + line+"\n");
                    bw.flush();
                    if (QUIT.equals(line)) {
                        log.info("客户端已断开连接：{}", accept.getPort());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ss != null) {
                try {
                    ss.close();
                    System.out.println("关闭serverSocket");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
